<!DOCTYPE html>
<html lang="{{ lang }}">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>语音录制</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}?v={{ version }}">
    <script>
        // 全局错误处理，防止浏览器扩展冲突
        window.addEventListener('error', function(event) {
            // 检查错误是否来自扩展
            if (event.filename && event.filename.includes('chrome-extension://')) {
                // 阻止错误传播
                event.stopPropagation();
                event.preventDefault();
                console.warn('已拦截来自浏览器扩展的错误:', event.message);
                return true;
            }
        }, true);
        
        // 拦截未处理的Promise错误
        window.addEventListener('unhandledrejection', function(event) {
            // 检查错误是否与消息端口相关
            if (event.reason && event.reason.message && 
                (event.reason.message.includes('message port') || 
                 event.reason.message.includes('port closed'))) {
                // 阻止错误传播
                event.stopPropagation();
                event.preventDefault();
                console.warn('已拦截消息端口错误:', event.reason.message);
                return true;
            }
        });

        // 存储Prolific参数
        window.prolificData = {
            pid: "{{ prolific_pid }}",
            studyId: "{{ prolific_study_id }}",
            sessionId: "{{ prolific_session_id }}"
        };
        
        // 存储应用配置
        window.appConfig = {
            repetitions: Number("{{ repetitions }}"),  // 重复次数 - 使用Number确保是数字
            commandWords: {{ command_words|tojson }},  // 指令词列表
            speeds: {{ speeds|tojson }},  // 速度设置
            platform: "{{ platform }}"  // 平台
        };
        
        // 在控制台输出Prolific参数，便于调试
        console.log('从服务器接收的Prolific参数:', window.prolificData);
        console.log('从服务器接收的应用配置:', window.appConfig);
        console.log('重复次数:', window.appConfig.repetitions, '类型:', typeof window.appConfig.repetitions);
        
        // 在页面加载完成后检查URL参数
        window.addEventListener('DOMContentLoaded', function() {
            const urlParams = new URLSearchParams(window.location.search);
            const prolificPID = urlParams.get('PROLIFIC_PID');
            const studyID = urlParams.get('STUDY_ID');
            const sessionID = urlParams.get('SESSION_ID');
            
            console.log('从URL获取的Prolific参数:', {
                prolificPID,
                studyID,
                sessionID
            });
            
            // 检查是否已完成任务
            const alreadyCompleted = "{{ already_completed }}" === "True";
            if (alreadyCompleted) {
                console.log('用户已完成任务，禁用录音功能');
                // 在页面加载完成后禁用录音功能
                setTimeout(function() {
                    disableRecordingFunctionality();
                }, 100);
            }
            
            // 初始化语言设置
            if (window.i18n) {
                window.i18n.initLanguage();
            }
        });
        
        // 禁用录音功能
        function disableRecordingFunctionality() {
            // 禁用所有按钮
            const buttons = document.querySelectorAll('.btn');
            buttons.forEach(function(button) {
                button.disabled = true;
                button.style.opacity = '0.5';
                button.style.cursor = 'not-allowed';
            });
            
            // 显示已完成消息
            const completionMessage = "{{ completion_message }}";
            if (completionMessage) {
                const messageContainer = document.createElement('div');
                messageContainer.className = 'completion-message';
                messageContainer.innerHTML = `
                    <p>${completionMessage}</p>
                    <button id="return-to-prolific" class="btn">返回Prolific</button>
                `;
                messageContainer.style.textAlign = 'center';
                messageContainer.style.margin = '20px 0';
                messageContainer.style.padding = '10px';
                messageContainer.style.backgroundColor = '#f8f9fa';
                messageContainer.style.borderRadius = '5px';
                
                // 插入到容器的顶部
                const container = document.querySelector('.container');
                container.insertBefore(messageContainer, container.firstChild);
                
                // 添加返回按钮的点击事件
                document.getElementById('return-to-prolific').addEventListener('click', function() {
                    const prolificPID = "{{ prolific_pid }}";
                    const studyID = "{{ prolific_study_id }}";
                    const sessionID = "{{ prolific_session_id }}";
                    
                    if (prolificPID && studyID) {
                        window.location.href = `https://app.prolific.com/submissions/complete?cc=C6686SEV&PROLIFIC_PID=${prolificPID}&STUDY_ID=${studyID}&SESSION_ID=${sessionID}`;
                    } else {
                        window.location.href = 'https://app.prolific.com/';
                    }
                });
            }
        }
    </script>
    <style>
        #language-selector-container {
            position: absolute;
            top: 10px;
            right: 10px;
            z-index: 1000;
        }
        
        #language-selector {
            padding: 8px 16px;
            border-radius: 4px;
            border: 1px solid #ccc;
            background-color: white;
            font-size: 14px;
            cursor: pointer;
        }
        
        /* RTL支持 */
        .rtl-layout {
            direction: rtl;
            text-align: right;
        }
        
        .rtl-layout .button-section {
            flex-direction: row-reverse;
        }
        
        .rtl-layout #language-selector-container {
            left: 10px;
            right: auto;
        }
    </style>
</head>
<body>
    <!-- 添加语言选择器容器 -->
    <div id="language-selector-container"></div>
    
    <!-- 添加平台信息的隐藏元素 -->
    <div id="platform-info" data-platform="{{ platform }}" style="display: none;"></div>
    
    <!-- Prolific参数的隐藏元素 -->
    <div id="prolific-params" 
         data-prolific-pid="{{ prolific_pid }}" 
         data-prolific-study-id="{{ prolific_study_id }}" 
         data-prolific-session-id="{{ prolific_session_id }}"
         data-already-completed="{{ already_completed }}"
         style="display: none;">
    </div>
    
    <div class="container">
        <div class="section prompt-section" id="prompt-section">
            <p data-i18n="promptTemplate">请以<span id="speed-indicator" class="highlight">正常</span>速度朗读当前词（白色框内）</p>
        </div>

        <!-- 单词显示区域 -->
        <div class="word-section">
            <div class="word prev-word" id="prev-word"></div>
            <div class="word current-word" id="current-word"></div>
            <div class="word next-word" id="next-word"></div>
        </div>

        <div class="section waveform-section">
            <div id="waveform"></div>
            <div class="time-indicators">
                <span id="current-time">00:00</span>
                <span id="total-time">00:00</span>
            </div>
        </div>

        <div class="section button-section">
            <button id="prev-btn" class="btn" data-i18n="prevBtn">上一词</button>
            <button id="record-btn" class="btn record-btn" data-i18n="recordBtn">录音</button>
            <button id="next-btn" class="btn" data-i18n="nextBtn">下一词</button>
        </div>
        
        <div id="loading-indicator" class="loading-indicator" style="display: none; text-align: center; margin: 10px 0;" data-i18n="loading">上传中...</div>

        <div class="section hint-section">
            <p data-i18n="hint1">请按录音按钮开始录音，每个单词将会重复<strong class="highlight">2</strong>遍，如果录音结果和单词不符，将被拒绝</p>
            <p data-i18n="next_word">每次读完一个词再点击下一词（不要在读的时候点击）</p>
            <p data-i18n="prev_word">重新录上一词点击上一词</p>
            <p data-i18n="recordingHint">录音时请保持安静的环境，清晰地念出每个单词</p>
            <p data-i18n="completeHint">完成所有单词后，将自动进入提交页面</p>
        </div>
        
        <div id="progress-container">
            <div class="progress-info">
                <span id="speed-progress" data-i18n="speedProgress">当前速度: </span>
                <span id="word-count">0/13</span>
            </div>
            <div class="progress-bar-container">
                <div id="progress-bar" class="progress-bar"></div>
            </div>
        </div>
    </div>

    <script src="{{ url_for('static', filename='js/libs/wavesurfer.min.js') }}?v={{ version }}"></script>
    <script src="{{ url_for('static', filename='js/i18n.js') }}?v={{ version }}"></script>
    <script src="{{ url_for('static', filename='js/modules/recorder.js') }}?v={{ version }}"></script>
    <script src="{{ url_for('static', filename='js/modules/storage-manager.js') }}?v={{ version }}"></script>
    <script src="{{ url_for('static', filename='js/modules/waveform.js') }}?v={{ version }}"></script>
    <script src="{{ url_for('static', filename='js/app.js') }}?v={{ version }}"></script>
</body>
</html> 